<template>
  <el-dialog v-model="props.visible" title="生产报工" width="80%" :before-close="handleClose" align-center>
    <div class="work-report-form">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="6">
            <!-- First Row -->
            <el-form-item label="报工类型" prop="feedbackType" class="required">
              <el-select v-model="form.feedbackType" placeholder="请选择报工类型" clearable>
                <el-option label="自行报工" value="SELF" />
                <el-option label="统一报工" value="UNI" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产工单" prop="workorderCode" class="required">
              <el-input v-model="form.workorderCode" placeholder="请选择生产工单">
                <template #append>
                  <el-button :icon="Search" @click="handleWorkorder" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">

            <!-- Second Row -->
            <el-form-item label="生产任务" prop="taskCode" class="required">
              <el-input v-model="form.taskCode" placeholder="请选择生产任务">
                <template #append>
                  <el-button :icon="Search" @click="handleTask" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单位">
              <el-input v-model="form.unitOfMeasure" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <!-- Third Row -->
            <el-form-item label="产品编码">
              <el-input v-model="form.itemCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input v-model="form.itemName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- Fourth Row -->
            <el-form-item label="报工人" prop="nickName" class="required">
              <el-input v-model="form.nickName" placeholder="请选择报工人" readonly>
                <template #append>
                  <el-button :icon="Search" @click="handleUser" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核人">
              <el-input v-model="form.recordNick" placeholder="请选择审核人" readonly>
                <template #append>
                  <el-button :icon="Search" @click="handleRecord" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <!-- Fifth Row -->
            <el-form-item label="报工数量">
              <el-input v-model="form.quantityFeedback" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合格数量">
              <el-input-number v-model="form.quantityQualified" :max="form.quantityUncheck" @change="qualifiedChange"
                :min="0" class="mx-2" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="不合格数量">
              <el-input-number v-model="form.quantityUnquanlified" @change="unquanlifiedChange" :min="0" class="mx-2" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="待检测数量">
              <el-input v-model="form.quantityUncheck" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- Sixth Row - Full Width -->
          <el-col :span="12">
            <el-form-item label="备注" class="col-span-2">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" rows="3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" class="col-span-2">
              <el-input v-model="form.specification" type="textarea" readonly rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <select-user v-if="userVisible" :visible="userVisible" @close="userVisible = false" @confirm="UserConfirm" />
      <select-user v-if="recordVisible" :visible="recordVisible" @close="recordVisible = false"
        @confirm="recordConfirm" />
      <select-workorder v-if="workorderVisible" :visible="workorderVisible" @close="workorderVisible = false"
        @confirm="workorderConfirm" />
      <select-pro-task v-if="proTaskVisible" :dialog-visible="proTaskVisible" :workorder-code="form.workorderCode"
        @close="proTaskVisible = false" @confirm="proTaskConfirm" />
    </div>
    <!-- Dialog Footer -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handleClose">返回</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import selectUser from "@/components/ProductionReport/selectUserDialog.vue"
import selectWorkorder from "@/components/ProductionReport/selectWorkorderDialog.vue"
import selectProTask from "@/components/ProductionReport/selectProTaskDialog.vue"
import { ElMessage } from "element-plus";
import { AddFeedback } from "@/apis/zyj/feedback.js";

const props = defineProps({
  visible: Boolean,
})
const emit = defineEmits(['close'])

const dialogVisible = ref(false)
const formRef = ref(null)

const userVisible = ref(false)
const recordVisible = ref(false)
const workorderVisible = ref(false)
const proTaskVisible = ref(false)

const form = reactive({
  feedbackType: '',//报工类型
  feedbackCode: '',//报工编号
  workstationId: '',//工作站id
  workstationCode: '',//工作站编码
  workstationName: '',//工作站名称
  workorderId: '',//生产工单id
  workorderCode: '',//生产工单编号
  workorderName: '',//生产工单名称
  routeCode: '',//工艺编码
  processCode: '',//工序编码
  processName: '',//工序名称
  taskId: '',//生产任务id
  taskCode: '',//生产任务编号
  unitOfMeasure: '',//单位
  itemId: '',//产品id
  itemCode: '',//产品编码
  itemName: '',//产品名称
  userId: '',//报工人id
  userName: '',//报工人
  nickName: '',//报告人昵称
  recordUserId: '',//审核人id
  recordUser: '',//审核人
  recordNick: '',//审核人昵称
  quantity: 0,//排产数量
  quantityFeedback: 0,//本次报工数量
  quantityQualified: 0,//合格数量
  quantityUnquanlified: 0,//不合格数量
  quantityUncheck: 0,//待检测数量
  remark: '',
  specification: '',//规格型号
  clientOrderCode: '',//客户订单号
  feedbackTime: '',//报工时间
  status: ''//状态
})

const resetForm = reactive({ ...form })

const rules = {
  feedbackType: [{ required: true, message: '请选择报工类型', trigger: 'change' }],
  workorderCode: [{ required: true, message: '请选择生产工单', trigger: 'blur' }],
  taskCode: [{ required: true, message: '请选择生产任务', trigger: 'blur' }],
  nickName: [{ required: true, message: '请选择报工人', trigger: 'blur' }]
}

const handleUser = () => {
  userVisible.value = true
}
const handleRecord = () => {
  recordVisible.value = true
}
const handleWorkorder = () => {
  workorderVisible.value = true
}
const handleTask = () => {
  proTaskVisible.value = true
}

const handleSave = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    form.feedbackTime = new Date()
    form.feedbackCode = createID()
    form.status = "PREPARE"
    AddFeedback(form).then(req => {
      if (req === '成功') {
        ElMessage.success('添加成功')
        handleClose()
      } else {
        ElMessage.error('添加失败')
      }
    })
    console.log("最后的数据", form)
  } catch (error) {
    ElMessage.error('请选中必选项')
  }
}

const handleClose = () => {
  Object.assign(form, resetForm);
  emit('close')
}

const UserConfirm = (row) => {
  form.userName = row.userName
  form.userId = row.userId
  form.nickName = row.nickName
}
const recordConfirm = (row) => {
  form.recordUser = row.userName
  form.recordUserId = row.userId
  form.recordNick = row.nickName
}
const workorderConfirm = (row) => {
  form.workorderId = row.workorderId
  form.workorderCode = row.workorderCode
  form.workorderName = row.workorderName
  form.unitOfMeasure = row.unitOfMeasure
  form.itemId = row.productId
  form.itemCode = row.productCode
  form.itemName = row.productName
  form.specification = row.productSpc
  form.clientOrderCode = row.clientOrderCode
}
const proTaskConfirm = (row) => {
  console.log("sss3", row)
  form.taskId = row.taskId
  form.taskCode = row.taskCode
  form.workstationId = row.workstationId
  form.workstationName = row.workstationName
  form.workstationCode = row.workstationCode
  form.routeCode = row.routeCode
  form.processCode = row.processCode
  form.processName = row.processName
  form.quantity = row.quantity
  form.quantityUncheck = parseInt(row.quantity) - parseInt(row.quantityProduced)
}
const qualifiedChange = (row) => {
  form.quantityFeedback = row + form.quantityUnquanlified
}
const unquanlifiedChange = (row) => {
  form.quantityFeedback = row + form.quantityQualified
}

function createID() {
  let code = 'BD';
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  code = code + year + month + strDate + Math.floor(Math.random() * 10000);
  return code;
}
</script>

<style scoped>
.work-report-form {
  padding: 20px;
}

.required :deep(.el-form-item__label)::before {
  content: '*';
  color: var(--el-color-danger);
  margin-right: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: right;
  gap: 12px;
  padding-top: 20px;
}
</style>